<template>
  <view class="forecast-result">
    <!-- 结果摘要 -->
    <view class="result-summary">
      <view class="summary-card">
        <text class="summary-label">预报时长</text>
        <text class="summary-value">{{ result.forecastDays }}天</text>
      </view>
      <view class="summary-card">
        <text class="summary-label">数据点数</text>
        <text class="summary-value">{{ result.data?.length || 0 }}</text>
      </view>
      <view class="summary-card">
        <text class="summary-label">峰值流量</text>
        <text class="summary-value">{{ peakFlow }} m³/s</text>
      </view>
      <view class="summary-card">
        <text class="summary-label">峰现时间</text>
        <text class="summary-value">{{ peakTime }}</text>
      </view>
    </view>

    <!-- 多版本对比选择 -->
    <view class="version-compare-selector" v-if="versions.length > 1">
      <text class="selector-label">叠加对比版本:</text>
      <view class="version-checkboxes">
        <label 
          v-for="version in versions" 
          :key="version.id"
          class="version-checkbox"
        >
          <input 
            type="checkbox" 
            :value="version.id"
            v-model="selectedVersions"
            @change="updateChart"
          />
          <text>{{ version.name }}</text>
        </label>
      </view>
    </view>

    <!-- 图表 -->
    <view class="chart-container">
      <canvas 
        canvas-id="resultChart" 
        id="resultChart"
        class="result-chart"
        :style="{ width: '100%', height: '500px' }"
      ></canvas>
    </view>

    <!-- 数据表格 -->
    <view class="data-table-section">
      <view class="table-header-bar">
        <text class="table-title">预报数据详情</text>
        <button class="export-table-btn" @click="exportTableData">
          📤 导出数据
        </button>
      </view>
      
      <view class="data-table-container">
        <view class="data-table-header">
          <text class="table-col col-time">时间</text>
          <text class="table-col col-flow">流量(m³/s)</text>
          <text class="table-col col-level">水位(m)</text>
          <text class="table-col col-volume">蓄量(万m³)</text>
        </view>
        <view class="data-table-body">
          <view 
            v-for="(item, index) in result.data" 
            :key="index"
            class="data-table-row"
            :class="{ peak: isPeak(item) }"
          >
            <text class="table-col col-time">{{ formatDateTime(item.time) }}</text>
            <text class="table-col col-flow">{{ item.flow.toFixed(2) }}</text>
            <text class="table-col col-level">{{ item.level?.toFixed(2) || '-' }}</text>
            <text class="table-col col-volume">{{ item.volume?.toFixed(2) || '-' }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="statistics-section">
      <text class="statistics-title">统计信息</text>
      <view class="statistics-grid">
        <view class="stat-item">
          <text class="stat-label">平均流量</text>
          <text class="stat-value">{{ avgFlow }} m³/s</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">最小流量</text>
          <text class="stat-value">{{ minFlow }} m³/s</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">累计径流量</text>
          <text class="stat-value">{{ totalRunoff }} 万m³</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">径流系数</text>
          <text class="stat-value">{{ runoffCoefficient }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

export default {
  name: 'ForecastResult',
  props: {
    result: {
      type: Object,
      required: true
    },
    versions: {
      type: Array,
      default: () => []
    }
  },
  emits: ['version-compare'],
  setup(props, { emit }) {
    const chartInstance = ref(null)
    const selectedVersions = ref([])

    // 计算峰值
    const peakFlow = computed(() => {
      if (!props.result?.data?.length) return '-'
      const max = Math.max(...props.result.data.map(item => item.flow))
      return max.toFixed(2)
    })

    const peakTime = computed(() => {
      if (!props.result?.data?.length) return '-'
      const peakItem = props.result.data.reduce((prev, curr) => 
        curr.flow > prev.flow ? curr : prev
      )
      return formatDateTime(peakItem.time)
    })

    const avgFlow = computed(() => {
      if (!props.result?.data?.length) return '-'
      const sum = props.result.data.reduce((acc, item) => acc + item.flow, 0)
      return (sum / props.result.data.length).toFixed(2)
    })

    const minFlow = computed(() => {
      if (!props.result?.data?.length) return '-'
      const min = Math.min(...props.result.data.map(item => item.flow))
      return min.toFixed(2)
    })

    const totalRunoff = computed(() => {
      if (!props.result?.data?.length) return '-'
      // 简单累计，实际需要根据时段长度计算
      const sum = props.result.data.reduce((acc, item) => acc + item.flow, 0)
      return (sum * 3 * 3600 / 10000).toFixed(2) // 3小时时段，转换为万m³
    })

    const runoffCoefficient = computed(() => {
      return props.result.runoffCoefficient?.toFixed(3) || '-'
    })

    const isPeak = (item) => {
      if (!props.result?.data?.length) return false
      const max = Math.max(...props.result.data.map(d => d.flow))
      return item.flow === max
    }

    const formatDateTime = (timeStr) => {
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 初始化图表
    const initChart = () => {
      nextTick(() => {
        const canvas = document.getElementById('resultChart')
        if (!canvas) return

        chartInstance.value = echarts.init(canvas)
        updateChart()
      })
    }

    // 更新图表
    const updateChart = () => {
      if (!chartInstance.value || !props.result?.data) return

      const series = []
      const legend = []

      // 当前结果
      series.push({
        name: '当前预报',
        type: 'line',
        data: props.result.data.map(item => item.flow),
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409eff'
        },
        itemStyle: {
          color: '#409eff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
            ]
          }
        }
      })
      legend.push('当前预报')

      // 添加选中的版本
      selectedVersions.value.forEach((versionId, index) => {
        const version = props.versions.find(v => v.id === versionId)
        if (version?.result?.data) {
          const colors = ['#67c23a', '#e6a23c', '#f56c6c', '#909399']
          const color = colors[index % colors.length]
          
          series.push({
            name: version.name,
            type: 'line',
            data: version.result.data.map(item => item.flow),
            smooth: true,
            lineStyle: {
              width: 2,
              type: 'dashed',
              color: color
            },
            itemStyle: {
              color: color
            }
          })
          legend.push(version.name)
        }
      })

      const option = {
        title: {
          text: '预报流量过程',
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter: (params) => {
            const item = props.result.data[params[0].dataIndex]
            let content = `<div style="font-weight: bold; margin-bottom: 8px;">${formatDateTime(item.time)}</div>`
            params.forEach(param => {
              content += `<div>${param.marker} ${param.seriesName}: ${param.value.toFixed(2)} m³/s</div>`
            })
            return content
          }
        },
        legend: {
          data: legend,
          top: 40,
          left: 'center'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: props.result.data.map(item => formatDateTime(item.time)),
          boundaryGap: false,
          axisLabel: {
            rotate: 45,
            formatter: (value) => {
              // 只显示部分标签
              return value.split(' ')[0]
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '流量(m³/s)',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: series,
        dataZoom: [
          {
            type: 'slider',
            show: true,
            start: 0,
            end: 100
          },
          {
            type: 'inside'
          }
        ]
      }

      chartInstance.value.setOption(option)
    }

    // 导出表格数据
    const exportTableData = () => {
      let csv = '时间,流量(m³/s),水位(m),蓄量(万m³)\n'
      props.result.data.forEach(item => {
        csv += `${formatDateTime(item.time)},${item.flow.toFixed(2)},${item.level?.toFixed(2) || ''},${item.volume?.toFixed(2) || ''}\n`
      })

      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `forecast_result_${Date.now()}.csv`
      link.click()
      
      uni.showToast({
        title: '导出成功',
        icon: 'success'
      })
    }

    watch(() => props.result, () => {
      updateChart()
    }, { deep: true })

    watch(() => props.versions, () => {
      updateChart()
    }, { deep: true })

    onMounted(() => {
      initChart()
    })

    return {
      selectedVersions,
      peakFlow,
      peakTime,
      avgFlow,
      minFlow,
      totalRunoff,
      runoffCoefficient,
      isPeak,
      formatDateTime,
      updateChart,
      exportTableData
    }
  }
}
</script>

<style scoped>
.forecast-result {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 结果摘要 */
.result-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.summary-card {
  padding: 16px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border-left: 3px solid #409eff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.summary-label {
  font-size: 13px;
  color: #606266;
}

.summary-value {
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
  font-family: 'Monaco', 'Courier New', monospace;
}

/* 版本对比选择器 */
.version-compare-selector {
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.selector-label {
  font-size: 14px;
  color: #303133;
  font-weight: 600;
}

.version-checkboxes {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.version-checkbox {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
}

/* 图表 */
.chart-container {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
}

.result-chart {
  width: 100%;
  height: 500px;
}

/* 数据表格 */
.data-table-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.table-header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.export-table-btn {
  padding: 8px 16px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s;
}

.export-table-btn:hover {
  border-color: #409eff;
  color: #409eff;
  background-color: #ecf5ff;
}

.data-table-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  max-height: 500px;
  overflow-y: auto;
}

.data-table-header {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr;
  background-color: #f5f7fa;
  border-bottom: 2px solid #e4e7ed;
  font-weight: 600;
  position: sticky;
  top: 0;
  z-index: 10;
}

.data-table-body {
  display: flex;
  flex-direction: column;
}

.data-table-row {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr;
  border-bottom: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.data-table-row:hover {
  background-color: #fafafa;
}

.data-table-row.peak {
  background-color: #fff7e6;
  font-weight: 600;
}

.table-col {
  padding: 12px 16px;
  font-size: 14px;
  color: #606266;
}

.col-flow,
.col-level,
.col-volume {
  font-family: 'Monaco', 'Courier New', monospace;
  color: #409eff;
  text-align: center;
}

/* 统计信息 */
.statistics-section {
  padding: 20px;
  background: linear-gradient(135deg, #fafafa 0%, #f5f7fa 100%);
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.statistics-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  display: block;
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
  font-family: 'Monaco', 'Courier New', monospace;
}
</style>

